<?php
/**
 * Created by PhpStorm.
 * User: xkq
 * Date: 2018/4/1 0001
 * Time: 19:12
 */

set_include_path(dirname(dirname(__FILE__)));
include_once("inc/init.php");
if (!session_id()) session_start();
action_log($_POST);
$action = crequest("action");
$action = $action == '' ? 'location' : $action;
switch ($action)
{
    case "location":
        location();
        break;
    case "panel_location":
        panel_location();
        break;
    case "get_send_order":
        get_send_order();
        break;
}

//function location(){
//    global $db;
//    $ordersn = $_POST['ordersn'];
//    $data['lat'] = isset($_POST['lat']) ? trim($_POST['lat']) : showapierror('lat_not_find');
//    $data['lng'] = isset($_POST['lng']) ? trim($_POST['lng']) : showapierror('lng_not_find');
//    $data['openid'] = isset($_POST['openid']) ? trim($_POST['openid']) : showapierror('openid_not_find');
//    $data['address'] = get_location($data['lat'],$data['lng']);
//    if (isset($data['openid']) && !empty($data['openid'])) {
//        $sql = "SELECT * FROM user_dingwei WHERE openid = '{$data['openid']}' ";
//        $user_dingwei = $db->get_row($sql);
//        if($user_dingwei && !empty($user_dingwei) && isset($user_dingwei['openid']) && !empty($user_dingwei['openid'])){
//            $data['last_login_time'] = time();
//            $db->update('user_dingwei',$data,"userid = '{$user_dingwei['userid']}'");
//        }else{
//            $data['nickname']    	= $_POST['nickName'];
//            $data['gender']    	= $_POST['gender'];
//            $data['openid']    	= $_POST['openId'];
//            $data['avatar']    	= $_POST['avatarUrl'];
//            $data['unionid']    	= $_POST['unionId'];
//            $data['add_time'] = time();
//            $data['add_time_format'] = now_time();
//            $data['last_login_time'] = time();
//            $db->insert('user',$data);
//        }
//
//        $sql = "SELECT * FROM `order` WHERE ordersn='{$ordersn}'";
//        $orderinfo = $db->get_row($sql);
//        if (!$orderinfo){
//            showapierror('order_insert_error');
//        }
//        $orderinfo['openid'] = $data['openid'];
//
//        $sql = "SELECT * FROM `send_order` WHERE ordersn='{$ordersn}'";
//        $send_order = $db->get_row($sql);
//        if(!$send_order){
//            $orderid = wx_payment($orderinfo);
//            $info['orderid'] = $orderid;
//            $info['ordersn'] = $ordersn;
//            $info['openid'] = $data['openid'];
//            $info['cost'] =  $orderinfo['cost'];
//            $db->insert('send_order',$info);
//            $sql = "SELECT * FROM `send_order` WHERE ordersn='{$ordersn}' and openid = '{$data['openid']}'";
//            $send_order = $db->get_row($sql);
//            showapisuccess($send_order);
//        }else{
//            showapierror('红包已被领取！');
//        }
//    }else{
//        showapierror('缺少参数！');
//    }
//
//}


function location(){
    global $db;
    $sid = $_POST['sid'];
    $data['lat'] = isset($_POST['lat']) ? trim($_POST['lat']) : showapierror('lat_not_find');
    $data['lng'] = isset($_POST['lng']) ? trim($_POST['lng']) : showapierror('lng_not_find');
    $data['openid'] = isset($_POST['openid']) ? trim($_POST['openid']) : showapierror('openid_not_find');
    $data['address'] = get_location($data['lat'],$data['lng']);
    if (isset($data['openid']) && !empty($data['openid'])) {
        $sql = "SELECT * FROM user_dingwei WHERE openid = '{$data['openid']}' ";
        $user_dingwei = $db->get_row($sql);
//        if($user_dingwei && !empty($user_dingwei) && isset($user_dingwei['openid']) && !empty($user_dingwei['openid'])){
//            $data['last_login_time'] = time();
//            $db->update('user_dingwei',$data,"userid = '{$user_dingwei['userid']}'");
//        }else{
            $data['sid']    	= $sid;
            $data['nickname']    	= $_POST['nickname'];
            $data['gender']    	= $_POST['sex'];
            $data['openid']    	= $_POST['openid'];
            $data['avatar']    	= $_POST['headimgurl'];
            $data['unionid']    	= $_POST['unionid'];
            $data['add_time'] = time();
            $data['add_time_format'] = now_time();
            $data['last_login_time'] = time();
            $data['type'] = $_POST['type'];
            if($data['type'] == 2){
                $data['ordersn'] = $_POST['ordersn'];
            }
            $db->insert('user_dingwei',$data);
            sendMessage($sid,$_POST['nickname'],$data['type'],$data['ordersn']);
//        }
        showapierror([],"更新成功");
    }else{
        showapierror('缺少参数！');
    }

}


function get_send_order(){
    global $db;
    if(!empty($_POST['userid'])) {
        $userid = $_POST['userid'];
        $sql = "SELECT * FROM `order` WHERE userid='{$userid}'";
        $orderinfo = $db->get_all($sql);
        foreach($orderinfo as $key=>$val){
            $sql = "SELECT * FROM `send_order` WHERE ordersn='{$val['ordersn']}'";
            $send_order = $db->get_row($sql);
            $sql = "SELECT * FROM `user_dingwei` WHERE openid='{$send_order['openid']}'";
            $user = $db->get_row($sql);
            $data[$key]['time'] = $send_order['add_time_format'];
            $data[$key]['address'] = $user['address'];
            $data[$key]['lat'] = $user['lat'];
            $data[$key]['lng'] = $user['lng'];
            $data[$key]['status'] = "已领取";
        }
        showapisuccess($data);

    }else{
        showapierror('缺少参数！');
    }
}


function get_location($lat,$lng){
    $url = "http://apis.map.qq.com/ws/geocoder/v1/?location=$lat,$lng&key=".TX_KEY;
    $result = httpGet($url);
    $result = json_decode($result,true);
    return $result['result']['address'];
}


/* 首先在服务器端调用微信【统一下单】接口，返回prepay_id和sign签名等信息给前端，前端调用微信支付接口 */
function wx_payment($info){
    global $db;
    if(empty($info['cost'])){
        showapierror('金额有误！');
    }
    $cost = intval($info['cost']*100);   //微信金额以分为单位
    if(empty($info['openid'])){
        showapierror('登录失效，请重新登录(openid参数有误)！');
    }

    //这里是按照顺序的 因为下面的签名是按照(字典序)顺序 排序错误 肯定出错
    $post['nonce_str'] = getNonceStr();//随机字符串
    $post['mch_billno'] = date('Ymd').substr(microtime(), 2,3).rand(1000,9999);//商户订单号
    $post['mch_id'] = MCH_ID; //商户号
    $post['wxappid'] =  APPID;//如果是公众号 就是公众号的appid;小程序就是小程序的appid
    $post['send_name'] = "辰锦科技";
    $post['re_openid'] = $info['openid'];
    $post['total_amount'] = $cost;
    $post['total_num'] = 1;
    $post['wishing'] = "一个转身，可以是一个结束；一个转身，也可以是一个新的开始。";
    $post['client_ip'] = real_ip();
    $post['act_name'] = "祝生活愉快";
    $post['remark'] = "一个转身，可以是一个结束；一个转身，也可以是一个新的开始。";
    $post['sign'] = MakeSign($post);              //签名
    $post_xml = arrayToXml($post);


    //统一下单接口prepay_id
    $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
    $xml = http_request($url,$post_xml);     //POST方式请求http
    $array = xmlToObject($xml);

    if($array['return_code'] == 'SUCCESS'){
        return $post['mch_billno'];

    }else{
        showapierror($array['return_msg']);
    }

}

/**
 * 生成签名, $KEY就是支付key
 * @return 签名
 */
function MakeSign( $params){
    //签名步骤一：按字典序排序数组参数
    ksort($params);
    $string = ToUrlParams($params);  //参数进行拼接key=value&k=v
    //签名步骤二：在string后加入KEY
    $string = $string . "&key=".WX_KEY;
    //签名步骤三：MD5加密
    $string = md5($string);
    //签名步骤四：所有字符转为大写
    $result = strtoupper($string);
    return $result;
}
/**
 * 将参数拼接为url: key=value&key=value
 * @param $params
 * @return string
 */
function ToUrlParams( $params ){
    $string = '';
    if( !empty($params) ){
        $array = array();
        foreach( $params as $key => $value ){
            $array[] = $key.'='.$value;
        }
        $string = implode("&",$array);
    }
    return $string;
}
/**
 * 调用接口， $data是数组参数
 * @return 签名
 */
function http_request($url,$data = null,$headers=array())
{
    $curl = curl_init();
    if( count($headers) >= 1 ){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
//获取xml里面数据，转换成array
function xmlToObject($xmlStr) {
    if (!is_string($xmlStr) || empty($xmlStr)) {
        return false;
    }
    $postObj = simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA);
    $postObj = json_decode(json_encode($postObj));
    return object_to_array($postObj);
}
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }

    return $obj;
}
function getNonceStr() {
    $code = "";
    for ($i=0; $i > 10; $i++) {
        $code .= mt_rand(10000);
    }
    $nonceStrTemp = md5($code);
    $nonce_str = mb_substr($nonceStrTemp, 5,37);
    return $nonce_str;
}


function arrayToXml($arr) {
    $xml = "<xml>";
    foreach ($arr as $key=>$val) {
        if (is_numeric($val)) {
            $xml.="<".$key.">".$val."</".$key.">";
        } else {
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}